import qrcode
import time
from logger import logger
from PySide6 import QtCore, QtWidgets
from PySide6.QtGui import QPixmap
from PIL.ImageQt import ImageQt
from utils.task import Task

class LoginWidget(QtWidgets.QWidget):
    def __init__(self, app):
        super().__init__()
        self.app = app
        self.resize(400, 400)
        self.setWindowTitle('Dokker 登陆')

        self.label = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)

        self.layout = QtWidgets.QVBoxLayout(self)
        self.layout.addWidget(self.label)
    
    def show(self):
        super().show()
        self.task = Task(self.login)
        self.task.over.connect(self.app.main_show)
        self.task.start()

    def closeEvent(self, event):
        self.task.quit()
        logger.info('login widget close')
        event.accept()

    def login(self):
        # 缓存获取token
        self.label.setText('正在自动登陆')
        self.app.login.load()
        while self.app.login.user == None:
            check = self.app.login.check_login()
            if check == False:
                # 显示二维码
                self.get_qrcode()
            # 延迟两秒
            time.sleep(2)

    def get_qrcode(self):
        # 生成二维码
        qr = qrcode.QRCode(border=2,box_size=5)
        # 使用 login 中获取登陆二维码
        qr.add_data(self.app.login.get_qrcode_url())
        # 转成 pyside 的图片格式
        qrcode_image = ImageQt(qr.make_image().convert("RGB"))
        # 显示 pixmap
        self.label.setPixmap(QPixmap.fromImage(qrcode_image))